package com.tdam.CommunicationManager;


import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;

public class MessagesService extends Service
{
	private final IBinder conection = new LocalBinder();
	private final long INTERVAL =60000;
	private ArrayList<Notificable> clients;
	private ArrayList<WebMailInfo> messages;
	private Timer timer;
	private final int NOTIFICATION_ID=0;

	@Override
	public void onCreate() 
	{
		super.onCreate();
		clients= new ArrayList<Notificable>();
		timer=new Timer();
		messages=new ArrayList<WebMailInfo>();
		timer.scheduleAtFixedRate( new TimerTask() {

			public void run() 
			{				
				Date timeStamp=new Date();
				timeStamp.setTime(timeStamp.getTime() - INTERVAL);
				ArrayList<WebMailInfo> newMessages=User.server.getMessages(timeStamp);
				int messagesCount=newMessages.size();
				if(messagesCount>0)
				{
					messages.addAll(newMessages);
					NotificationManager notificationManager = 
						(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
					Notification messageStatus=new Notification(R.drawable.vignette,"(" + 
							messagesCount + ")" +  MessagesService.this.getString(R.string.newMessages)
							,System.currentTimeMillis());
					messageStatus.flags= Notification.FLAG_AUTO_CANCEL; 
					Context context = getApplicationContext(); 
					CharSequence contentTitle =MessagesService.this.getString(R.string.app_name);
					CharSequence contentText =MessagesService.this.getString(R.string.newMessages);
					Intent notificationIntent = new Intent(MessagesService.this, Initial.class); 
					notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					PendingIntent contentIntent = PendingIntent.getActivity(MessagesService.this, 0, notificationIntent , 0);
					messageStatus.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
					notificationManager.notify(NOTIFICATION_ID,messageStatus);		
				}
			}

			}, 0L, INTERVAL);

			
	}
	
	
	
	@Override
	public IBinder onBind(Intent arg0) 
	{
		return conection;
	}
	
	public void bind(Notificable client)
	{
		clients.add(client);
	}

	public void unBind(Notificable client) 
	{
		clients.remove(client);
	}
	
	public class LocalBinder extends Binder
	{
		MessagesService getService() 
		{
			return MessagesService.this;
		}
	}
	public interface Notificable {

		boolean notificar(int acccion, Bundle datos);
	}
	
	public ArrayList<WebMailInfo> getMessages()
	{
		ArrayList<WebMailInfo> newMessages=messages;
		messages=new ArrayList<WebMailInfo>();
		return newMessages;
	}
	
}
